import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class CustomWebView extends StatefulWidget {
  final String initialUrl;

  const CustomWebView({Key? key, required this.initialUrl}) : super(key: key);

  @override
  _CustomWebViewState createState() => _CustomWebViewState();
}

class _CustomWebViewState extends State<CustomWebView> {
  late InAppWebViewController _webViewController;
  late InAppWebViewSettings inAppWebViewSettings;

  @override
  void initState() {
    super.initState();
    inAppWebViewSettings = InAppWebViewSettings(
      // 基础设置
      useShouldOverrideUrlLoading: true, // 是否拦截URL加载
      javaScriptEnabled: true, // 启用JavaScript
      javaScriptCanOpenWindowsAutomatically: false, // 禁止JS自动打开窗口
      loadWithOverviewMode: true, // 自适应屏幕
      useWideViewPort: true, // 支持宽视图

      // 缓存设置
      cacheMode: CacheMode.LOAD_DEFAULT, // 默认缓存模式
      domStorageEnabled: true, // 启用DOM存储
      databaseEnabled: true, // 启用数据库存储

      // 界面设置
      allowsInlineMediaPlayback: true, // 允许视频内联播放
      mediaPlaybackRequiresUserGesture: true, // 媒体播放需要用户交互
      supportZoom: true, // 支持缩放
      builtInZoomControls: true, // 显示缩放控件
      displayZoomControls: false, // 隐藏原生缩放控件（通常配合自定义控件）

      // 安全设置
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW, // 允许混合内容
      // safeBrowsingEnabled: true, // 启用安全浏览

      // 其他实用设置
      useOnDownloadStart: true, // 监听下载事件
      // allowFileAccess: false, // 禁止访问本地文件
      // allowContentAccess: false, // 禁止通过内容URL访问

      // userAgent: "Custom User Agent", // 自定义User Agent
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("WebView Example"),
      ),
      body: InAppWebView(

        initialUrlRequest: URLRequest(url:WebUri(widget.initialUrl)),
        initialSettings: inAppWebViewSettings,
        onWebViewCreated: (InAppWebViewController controller) {
          _webViewController = controller;
        },
        onLoadStart: (controller, url) {
          print("Started loading: $url");
        },
        onLoadStop: (controller, url) {
          print("Finished loading: $url");
        },
        onProgressChanged: (controller, progress) {
          print("Loading progress: $progress%");
        },
      ),
    );
  }
}
